這篇稍微介紹 ORM 操作資料庫關聯的用法。「1對1」和「1對多」作法相同,須在自己的 tabel 加 Foreign Key,「多對多」需要建立一個關聯表(pivot table)。 感謝 Charleen 的文章-Eloquent: Many to Many (前言:創建多對多資料表,踩坑大全)
舉餐廳的例子:
public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->unsignedBigInteger('restaurant_id');
        }
    }
2-1. 在 menu 自己的 Model 中加入 restaurant 函式,用 belongsTo 取出關聯的資料
public function restaurant(){
    return $this->belongsTo('App\Restaurant');
}
2-2. 或是在 restaurant 的 Model 中加入 menu 函式,用 hasOne 或是 hasMany 取出關聯的資料
public function menu()
    {
        return $this->hasOne('App\Menu');
    }
}
Restaurant::with('users')->first()->menu;
{
"id": 1,
"img": "http://localhost:8000/storage/JQmggLcgfEqweLSMzqoqm4x8WV4DIaU5RitsYgjX.jpeg",
"restaurant_id": 1
}
Restaurant::with('menu')->first();
{
"id": 1,
"name": "veg_sasa",
"menu": {
"id": 1,
"img": "http://localhost:8000/storage/JQmggLcgfEqweLSMzqoqm4x8WV4DIaU5RitsYgjX.jpeg",
"restaurant_id": 1
}
}
php artisan make:migration create_restaurant_user_tablephp artisan make:model RestaurantUser
若是直接用
php artisan make:model UserRestaurant -mc,會自動產生有複數的 table(user_restaurants),這樣會有錯
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testorm.restaurant_user' doesn't exist
protected $table = 'restaurant_user'; 若model中沒有特地寫這行, model會沒辦法對應到資料庫的 table, 因為他會去找預設的 restaurant_users 來作存取public function users()
    {
        return $this->belongsToMany('App\User');
    }
protected $hidden = [
        'password', 'remember_token','created_at', 'updated_at','pivot'
    ];
User::with('restaurants')->latest('id')->first();
{
    "id": 2,
    "name": "erin",
    "restaurants": [
        {
            "id": 1,
            "name": "veg_sasa"
        },
        {
            "id": 2,
            "name": "veg_elephant"
        }
    ]
}
反向撈關聯資料 Restaurant::with('users')->latest('id')->first();
{
    "id": 2,
    "name": "veg_elephant",
    "users": [
        {
            "id": 2,
            "name": "erin"
        },
        {
            "id": 1,
            "name": "sarah"
        }
    ]
}